package com.sk.skplanet.commute.actions;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Vector;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import com.sk.skplanet.commute.exceptions.BusAPIException;
import com.sk.skplanet.commute.vo.Data;
import com.sk.skplanet.commute.vo.Point;
import com.sk.skplanet.commute.vo.Route;
import com.sk.skplanet.commute.vo.StopInfo;

public class InsertTask extends AsyncTask<Void, String, Boolean> {
	private ProgressDialog dialog;
	private Route route;
	private Point point;
	private StopInfo stopInfo;
	private Context context;

	private JSONObject result;

	public InsertTask(Context context, Route route) {
		this.context = context;
		this.route = route;
	}

	public InsertTask(Context context, Point point) {
		this.context = context;
		this.point = point;
	}

	public InsertTask(Context context, StopInfo stopInfo) {
		this.context = context;
		this.stopInfo = stopInfo;
	}

	@Override
	protected Boolean doInBackground(Void... unused) {
		try {
			// Thread.sleep(2000);

			// /bus/saveroute.json
			// argument
			// name : 대분류명
			// member_id : 소유 사용자 고유번호
			result = new JSONObject();
			Vector<NameValuePair> nameValue = new Vector<NameValuePair>();
			nameValue.add(new BasicNameValuePair("auth_key", Data.AUTH_KEY));

			if (route != null) {
				nameValue.add(new BasicNameValuePair("name", route.getName()));
				nameValue.add(new BasicNameValuePair("member_id", Long.toString(route.getMember_id())));
				result = getJSON(Data.URL_DEFAULT + Data.URL_SETROUTE, nameValue);
			} else if (point != null) {
				nameValue.add(new BasicNameValuePair("name", point.getName()));
				nameValue.add(new BasicNameValuePair("route_id", Long.toString(point.getRoute_id())));
				result = getJSON(Data.URL_DEFAULT + Data.URL_SETPOINT, nameValue);
			} else if (stopInfo != null) {
				nameValue.add(new BasicNameValuePair("stop_id", stopInfo.getStop_id()));
				nameValue.add(new BasicNameValuePair("bus_id", stopInfo.getBus_id()));
				nameValue.add(new BasicNameValuePair("stop_name", stopInfo.getStop_name()));
				nameValue.add(new BasicNameValuePair("bus_name", stopInfo.getBus_name()));
				nameValue.add(new BasicNameValuePair("point_id", Long.toString(stopInfo.getPoint_id())));
				nameValue.add(new BasicNameValuePair("bus_type", stopInfo.getBus_type()));
				result = getJSON(Data.URL_DEFAULT + Data.URL_SETSTOPINFO, nameValue);
			} else {
				return false;
			}
		} catch (BusAPIException e) {
			e.printStackTrace();
			return false;	
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

		return true;
	}

	@Override
	protected void onPreExecute() {
		dialog = ProgressDialog.show(context, "", "추가하는 중입니다.", true);
	}

	@Override
	protected void onProgressUpdate(String... item) {
	}

	@Override
	protected void onPostExecute(Boolean success) {
		if (dialog != null) dialog.dismiss();

		if (result != null) {
			try {
				JSONObject data;

				data = result.getJSONObject("data");

				if (route != null) {
					route.setId(data.getInt("id"));
				} else if (point != null) {
					point.setId(data.getInt("id"));
				} else if (stopInfo != null) {
					stopInfo.setId(data.getInt("id"));
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		if (success) Toast.makeText(context, "등록이 완료되었습니다.", Toast.LENGTH_SHORT).show();
		else Toast.makeText(context, "서버와의 통신이 실패하였습니다.", Toast.LENGTH_SHORT).show();
	}

	private JSONObject getJSON(String URL, List<NameValuePair> params) throws IOException, JSONException,
			BusAPIException {
		String paramString = URLEncodedUtils.format(params, Data.ENCODING);
		String url = URL + "?" + paramString;

		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(url);

		InputStream is = httpclient.execute(httpget).getEntity().getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(is, Data.ENCODING));
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null)
			sb.append(line + "\n");
		is.close();

		JSONObject result = new JSONObject(sb.toString());

		if (result.getString("success").equals("ERROR")) throw new BusAPIException(result.getString("message"));

		return result;
	}
}
